package org.myontology.specialpages.configs;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import model.Vocabulary;

import org.myontology.specialpages.EntryRow;
import org.myontology.specialpages.helpers.LanguageCheck;
import org.openrdf.model.vocabulary.RDF;
import org.openrdf.model.vocabulary.RDFS;
import org.openrdf.query.BindingSet;
import org.openrdf.query.QueryLanguage;
import org.openrdf.query.TupleQuery;
import org.openrdf.query.TupleQueryResult;
import org.openrdf.repository.RepositoryConnection;

import controller.sesameDataConnector.AbstractDataConnector;

public class DomainNotEnglishLabelPage extends NotEnglishLabelPage {

	private static final String CONCEPT_QUERY="SELECT DISTINCT l,t,u,c FROM {u} <"+RDFS.LABEL+"> {l};<"+RDF.TYPE+"> {t};<"+Vocabulary.BELONGSTOONTOLOGYMODULE+"> {x};[<"+RDFS.COMMENT+"> {c}]  WHERE x=<http://myontology.org/v0/OntologyModule/Smart_Assistant> ";
	private static final String ATTRIBUTE_QUERY="SELECT DISTINCT l,t,u,c FROM {u} <"+RDFS.LABEL+"> {l};<"+RDF.TYPE+"> {t};<"+Vocabulary.DOMAIN+"> {x};[<"+RDFS.COMMENT+"> {c}] WHERE x=<";
	
	public DomainNotEnglishLabelPage() {
		super(CONCEPT_QUERY,"domain");
	}

	
	protected List<EntryRow> select() {
		query = CONCEPT_QUERY;
		List<EntryRow> concepts = super.select();
		List<EntryRow> list = preselect();
		List<EntryRow> props = new ArrayList<EntryRow>();
		for (Iterator<EntryRow> it = list.iterator();it.hasNext();) {
			EntryRow e = it.next();
			query = ATTRIBUTE_QUERY+e.getId()+">";
			props.addAll(super.select());
		}
		concepts.addAll(props);
		return concepts;
	}
	
	
	protected List<EntryRow> preselect() {
		
		List<EntryRow> ret = new ArrayList<EntryRow>();
		LanguageCheck check = new LanguageCheck();
		try{
			RepositoryConnection con = AbstractDataConnector.getConnection();	
			try {
				logger.info("special page query: "+query);
				TupleQuery tupleQuery = con.prepareTupleQuery(QueryLanguage.SERQL, query);
				TupleQueryResult result = tupleQuery.evaluate();
				try {
					if( result.hasNext()) {
								
						while (result.hasNext()) {
							BindingSet set = result.next();
							
							EntryRow row = writeSetToRow(set);
							String label = row.getLabel();
							ret.add(row);
						}
					}
				} finally {
					result.close();
				}
			} 
			catch (Exception e) {
				logger.error(e.getMessage());
			}
			finally {
				con.close();
			}
		} catch (Exception e) {
			logger.error("Error while selecting " + e.getMessage());
			return null;
		}
		return ret;
		
		
	}
	
}
